import React, {Component} from 'react';
import {
    Text, TextInput, TouchableOpacity, View, Alert, StyleSheet, AsyncStorage, FlatList, Image,
    ScrollView
} from 'react-native';
import CountEmitter from './../../utils/event/CountEmitter';
import {BasicStyle} from "../../../style/BasicStyle";
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';

export default class AddressList extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: "管理收货地址",
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerRight: <TouchableOpacity/>
    });

    constructor(props) {
        super(props);
        this.state = ({
            listView: null,
            loadingStatus: false,
        })
    }

    componentWillMount() {
        CountEmitter.addListener('addressListRefresh', () => {
            console.log("刷新监听");
            this._getDatas();
        });
    }

    componentDidMount() {
        this._getDatas();
    }

    componentWillUnmount() {
        CountEmitter.removeListener('addressListRefresh', () => {
        });
    }

    render() {
        return (
            <View style={[BasicStyle.containerView, styles.containerView]}>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>

                <ScrollView style={BasicStyle.containerView}>
                    {this.state.listView}
                </ScrollView>

                <TouchableOpacity style={styles.addButStyle} onPress={() => {
                    let {navigate} = this.props.navigation;
                    navigate('AddressEditNav');
                }}>
                    <Text style={[BasicStyle.commonFontText, styles.addButText]}>添加新地址</Text>
                </TouchableOpacity>
            </View>
        )
    }

    /*获取数据*/
    _getDatas = () => {
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/user/addresslist', xToken, '', (res) => {
                console.log(res);
                if (res.code === 200) {
                    this.setState({
                        listView: this._makeList(res.apiData),
                    });

                } else {
                    Toast.showShortBottom("错误：" + res.apiData);
                }
            });
        });
    };

    /*生成列表*/
    _makeList = (list) => {
        let listView = list.map((item) => {
            return <View key={item.id} style={styles.addrListItemView}>
                <View style={styles.addrListItemTitleView}><Text
                    style={[BasicStyle.commonFontLittleText, {marginLeft: utils.autoWidth(16)}]}>收货人：{item.consignee}</Text></View>
                <View style={styles.addrListItemTitleView}><Text
                    style={[BasicStyle.commonFontLittleText, styles.addrListItemTitleText]}>收货地址：{item.address}</Text></View>
                <View style={styles.addrListItemTitleView}><Text
                    style={[BasicStyle.commonFontLittleText, styles.addrListItemTitleText]}>联系手机：{item.telephone}</Text></View>

                <View style={styles.addrListItemOperationView}>
                    <TouchableOpacity style={styles.addrListItemDefaultBut}
                                      onPress={() => Alert.alert('温馨提示', '确定设置为默认地址吗?', [
                                          {text: '取消'},
                                          {
                                              text: '确定', onPress: () => this._makeDefaultAddr(item.id)

                                          }
                                      ])}>
                        {item.type === 1 ?
                            <Image style={styles.addrImg} source={require('./../../../img/selected_addr.png')}/>
                            :
                            <Image style={styles.addrImg} source={require('./../../../img/unselected_addr.png')}/>
                        }
                        <Text style={[BasicStyle.commonFontLittleText, styles.addrListItemDefaultText]}>默认地址</Text>
                    </TouchableOpacity>
                    <View style={BasicStyle.commonFlexRow}>
                        <TouchableOpacity style={BasicStyle.commonFlexRow}
                                          onPress={() => this._editAddr(item.id)}>
                            <Image style={styles.operationImg} source={require('./../../../img/edit_addr.png')}/>
                            <Text style={[BasicStyle.commonFontLittleText, styles.addrListItemOperationText]}>编辑</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={BasicStyle.commonFlexRow}
                                          onPress={() => Alert.alert('温馨提示', '确定删除该地址吗?', [
                                              {text: '取消'},
                                              {
                                                  text: '确定',

                                              }
                                          ])}>
                            <Image style={styles.operationImg} source={require('./../../../img/delete_addr.png')}/>
                            <Text style={[BasicStyle.commonFontLittleText, styles.addrListItemOperationText]}>删除</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        });

        return listView;
    };

    /*设置默认地址*/
    _makeDefaultAddr = (id) => {
        let params = {
            addrId: id
        };
        AsyncStorage.getItem("XToken").then((xToken) => {
            console.log(params);
            FetchUtils.postWithParamHeader(utils.apiUrl + '/user/defaultaddress', id, xToken, (res) => {
                if (res.code !== 200) {
                    Toast.showShortBottom("操作错误：" + res.apiData);
                    this.setState({
                        loadingStatus: false,
                    })
                } else {
                    Toast.showShortBottom("操作成功");
                    CountEmitter.emit("addressRefresh");//刷新地址
                    this._getDatas();
                }
            });
        });
    };
    /*删除地址*/
    _removeAddr = (id) => {
        let params = {
            addrId: id
        };
        AsyncStorage.getItem("XToken").then((xToken) => {
            console.log(params);
            FetchUtils.postWithParamHeader(utils.apiUrl + '/user/removeaddress', id, xToken, (res) => {
                if (res.code !== 200) {
                    Toast.showShortBottom("操作错误：" + res.apiData);
                    this.setState({
                        loadingStatus: false,
                    })
                } else {
                    Toast.showShortBottom("操作成功");
                    this._getDatas();
                }
            });
        });
    };
    /*编辑地址*/
    _editAddr = (id) => {
        let {navigate} = this.props.navigation;
        navigate('AddressEditNav', {id: id});
    }

}

const styles = StyleSheet.create({
    containerView: {
        justifyContent: 'space-between'
    },
    addrListItemView: {
        height: utils.autoheight(175),
        backgroundColor: '#FFF',
        marginBottom: utils.autoheight(20),
    },
    addrListItemTitleView: {
        height: utils.autoheight(44),
        borderBottomWidth: utils.autoheight(0.5),
        borderColor: '#E5E5E5',
        justifyContent: 'center'
    },
    addrListItemTitleText: {
        marginLeft: utils.autoWidth(16)
    },
    addrListItemOperationView: {
        height: utils.autoheight(44),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    addrListItemDefaultBut: {
        flexDirection: 'row',
        marginLeft: utils.autoWidth(16)
    },
    addrListItemDefaultText: {
        marginLeft: utils.autoWidth(10)
    },
    addrListItemOperationText: {
        marginRight: utils.autoWidth(16),
        marginLeft: utils.autoWidth(5)
    },
    addButText: {
        color: '#FFF'
    },
    addButStyle: {
        height: utils.autoheight(44),
        width: utils.screenWidth,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
    },
    addrImg: {
        height: utils.autoWidth(20),
        width: utils.autoWidth(20),
    },
    operationImg: {
        height: utils.autoheight(25),
        width: utils.autoWidth(18),
    }
});